//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: MsSqlCompactStorage.cs
//
//  Description: Provides a storage class for Microsoft SQL Server 2005
//               Compact Edition.
// 
//--------------------------------------------------------------------------

using System;
using System.Data.SqlClient;
using System.Reflection;
using System.Data;
using System.Data.Common;
using System.Data.SqlServerCe;
using Chili.Opf3.Query;
using Chili.Opf3;
using Chili.Opf3.Storages;
using Chili.Opf3.Query.OPathParser;

namespace Chili.Opf3.Storages.MsSqlCompact
{
	/// <summary>Storage class that encapsulates a pyhsical Microsoft SQL Server 2005 Compact Edition database.</summary>
	/// <remarks>
	/// <para>
	/// This class encapsulates a physical Microsoft SQL Server 2005 Compact Edition database. It is used to access to
	/// an Microsoft SQL Server 2005 Compact Edition database that is installed somewhere on your or on a remote machine. The storage
	/// implements the basic interfaces, such as <see cref="Opf3.Storages.IStorage">IStorage</see> for the basic storage IO
	/// functinality and <see cref="Opf3.Storages.ITransactionStorage">ITransactionStorage</see> for the transaction management.
	/// </para>
	/// <para>
	/// <b>Attention:</b> You should not access the methods of the storage directly but instead register the storage with your 
	/// instances of the <see cref="Opf3.ObjectContext">ObjectContext</see>. The <see cref="Opf3.ObjectContext">ObjectContext</see> 
	/// accesses the methods internally to get the objects from the storage.
	/// </para>
	/// </remarks>
	/// <example>
	///	 The following example shows how you should use the Microsoft SQL Server 2005 Compact Edition storage in your
	///	 applications. 
	///	 <code lang="CS">
	/// // ... Other code
	///  
	/// // Creates a new ObjectContext that uses a Sql Compact database as storage.
	/// // You should only pass an instance of the storage to your ObjectContext.
	/// // That's it! Nothing more. The methods of the storage are accessed
	/// // by the context internally.
	/// ObjectContext context = new ObjectContext(
	///	 new MsSqlCompactStorage("... some ConnectionString ..."));
	///  
	/// // ... Other code
	///	 </code>
	/// </example>
	public class MsSqlCompactStorage : SqlStorageBase
	{
		/// <summary>
		/// Creates a new instance of the <see cref="MsSqlCompactStorage">MsSqlCompactStorage Class</see>.
		/// </summary>
		/// <param name="connectionString">Specifies a string that contains the information (for ADO.NET) to connect to storage.</param>
		/// <exception cref="ArgumentNullException">ConnectionString is null.</exception>
		public MsSqlCompactStorage(string connectionString)
			: base(connectionString)
		{
			base.StorageCommandBuilders.Add(new MsSqlCompactCommandBuilder());
			base.StorageCommandBuilders.Add(new SqlQueryCommandBuilder());
		}

		/// <summary>
		/// Creates a new instance of the <see cref="MsSqlCompactStorage">MsSqlCompactStorage Class</see>.
		/// </summary>
		/// <param name="path">Specifies the path of the database.</param>
		/// <param name="fileName">Specifies the file name of the database.</param>
		/// <exception cref="ArgumentNullException">FileName is null.</exception>
		/// <exception cref="ArgumentNullException">Path is null.</exception>
		public MsSqlCompactStorage(string path, string fileName)
			: this(string.Format(@"Data Source = {0}\{1}", path, fileName))
		{
			if (path == null)
				throw new ArgumentNullException("path");
			if (fileName == null)
				throw new ArgumentNullException("fileName");
		}

		#region Overridden Members

		/// <summary>
		/// Executes a command on the storage that does not expect any results. It the method
		/// returns an argument it is used by the framework to set the
		/// <see cref="Opf3.FieldAttribute.AutoNumber">AutoNumber</see> property of the persistent
		/// object.
		/// </summary>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageConstraintException">A constraint of the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.ForeignKeyViolationException">A foreign key in the storage 
		/// has been violated.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">A duplicate primary key 
		/// is inserted in the storage.</exception>
		/// <exception cref="Opf3.Storages.PrimaryKeyViolationException">An index has been violated.</exception>
		/// <exception cref="Opf3.Storages.StorageException">Any other unexpected storage exception.</exception>
		public override object ExecuteCommand(IQuery query)
		{
			if (query == null)
				throw new ArgumentNullException("query");

			try
			{
				object autoValue = null;
				CompiledQuery compiledQuery = query.ToCompiledQuery(this);
				Tracing.Current.TraceStorageIO(compiledQuery);

				// Prepare the command for execution.
				using (IDbCommand dbCommand = this.PrepareCommand(compiledQuery))
				{
					// Execute the command without fetching the identity value. Not required, since we have no 
					// properties marked with AutoNumber = true.
					dbCommand.ExecuteNonQuery();

					// Check if we have to add the scope_identity flag to get the identity value.
					if (query.QueryType == QueryTypes.Insert && compiledQuery.AutoNumberItems != null)
					{
						IDbCommand cmd = new SqlCeCommand("select @@IDENTITY");
						cmd.Connection = dbCommand.Connection;
						if (dbCommand.Transaction != null)
							cmd.Transaction = dbCommand.Transaction;

						autoValue = cmd.ExecuteScalar();

						Tracing.Current.TraceStorageIO("Autonumber value returned: " + autoValue);
					}

					// If no transaction is active we can close the connection after executing the command.
					if (!IsTransactionActive)
						dbCommand.Connection.Close();
				}
				return autoValue;
			}
			catch (SqlException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>
		/// Executes and compiles the <see cref="Opf3.Query.IQuery">IQuery</see> and returns
		/// an <see cref="Opf3.ObjectReader{T}">ObjectReader</see> with the resultsset.
		/// </summary>
		/// <param name="context">
		/// 	<see cref="Opf3.ObjectContext">ObjectContext</see> that is connected with the
		/// <see cref="Opf3.ObjectReader{T}">ObjectReader</see>.
		/// </param>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		/// <exception cref="Opf3.Storages.StorageException">An unexpected storage exception has happened.</exception>
		public override ObjectReader<T> ExecuteReader<T>(ObjectContext context, IQuery query)
		{
			try
			{
				return base.ExecuteReader<T>(context, query);
			}
			catch (SqlCeException ex)
			{
				throw new StorageException(ex.Message, ex, query);
			}
		}

		/// <summary>Creates a new storage dependent connection object.</summary>
		/// <returns>Returns an instance of a storage dependent connection object.</returns>
		public override IDbConnection CreateConnection()
		{
			SqlCeConnection connection = new SqlCeConnection(this.ConnectionString);
			connection.Open();
			return connection;
		}

		/// <summary>Creates a new storage dependent command object.</summary>
		/// <returns>Returns an instance of a storage dependent command object.</returns>
		public override IDbCommand CreateCommand()
		{
			return new SqlCeCommand();
		}

		/// <summary>Creates and populates a storage dependent parameter with data.</summary>
		/// <returns>
		/// The name of the storage parameter should be set to a valid parameter name (one
		/// that is supported by the storage) while creating the parameter.
		/// </returns>
		/// <param name="index">Index of the storage parameter.</param>
		/// <param name="name">Name of the storage parameter.</param>
		/// <param name="value">Value of the storage parameter.</param>
		/// <param name="type">The type of the value argument. This information is useful if the value is null.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override IDataParameter CreateParameter(int index, ref string name, object value, Type type)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			// Set the name for the parameter.
			name = "@" + name;
			return new SqlCeParameter(name, value == null ? DBNull.Value : value);
		}

		/// <summary>
		/// Routine that prepares the command. Associates the command with a connection and
		/// populates it with data from the <see cref="Opf3.Query.IQuery">IQuery</see>.
		/// </summary>
		/// <param name="query">
		/// 	<see cref="Opf3.Query.IQuery">IQuery</see> that is compiled and executed on the
		/// storage.
		/// </param>
		protected override IDbCommand PrepareCommand(CompiledQuery query)
		{
			// Get the transaction connection.
			IDbConnection connection = (this.ActiveTransaction != null) ? ((SqlTransactionBase)this.ActiveTransaction).InnerTransaction.Connection : CreateConnection();

			// Create a new command object.
			IDbCommand command = query.Command;
			command.Connection = connection;
			if (this.ActiveTransaction != null)
				command.Transaction = ((SqlTransactionBase)this.ActiveTransaction).InnerTransaction;

			// Throw an exception if the connection is null!
			if (command.Connection == null)
			{
				throw new InvalidOperationException(string.Format("Connection for command is null. Transaction state: {0}",
					((SqlTransactionBase)this.ActiveTransaction).InnerTransaction));
			}

			return command;
		}

		/// <summary>Transforms the parameter to a valid field.</summary>
		/// <returns>Returns a string that represents a valid field name.</returns>
		/// <remarks>
		/// This method returns a field name that is valid for the current storage. For some
		/// storages it is a better choice to start each field name with a '[' and end with a ']'
		/// (Ms Access) - This method could wrap each field name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name for the field that is transformed.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidFieldName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			return string.Format("[{0}]", name);
		}

		/// <summary>
		/// Transforms the name of the entity to a valid entity name.
		/// </summary>
		/// <returns>Returns a string that represents a valid entity name.</returns>
		/// <remarks>
		/// This method returns an entity name that is valid for the current storage. For
		/// some storages it is a better choice to start each entity name with a '[' and end with a
		/// ']' (Ms Access) - This method could wrap each entity name passed with '[]'.
		/// </remarks>
		/// <param name="name">Name of the entity.</param>
		/// <exception cref="ArgumentNullException">Name is null.</exception>
		public override string GetValidEntityName(string name)
		{
			if (name == null)
				throw new ArgumentNullException("name", "Name is null.");

			return string.Format("[{0}]", name);
		}

		#endregion
	}
}
